
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './MyPosts.css';

const MyPosts = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 获取当前用户的帖子
    const fetchPosts = async () => {
      try {
        const response = await axios.get('/api/posts/my-posts');
        setPosts(response.data);
        setLoading(false);
      } catch (error) {
        console.error('获取帖子失败:', error);
        setLoading(false);
      }
    };

    fetchPosts();
  }, []);

  const handleDelete = async (postId) => {
    try {
      await axios.delete(`/api/posts/${postId}`);
      setPosts(posts.filter(post => post._id !== postId));
    } catch (error) {
      console.error('删除帖子失败:', error);
    }
  };

  if (loading) return &lt;div&gt;加载中...&lt;/div&gt;;

  return (
    &lt;div className="my-posts-container"&gt;
      &lt;h1&gt;我的帖子&lt;/h1&gt;
      &lt;div className="posts-grid"&gt;
        {posts.map(post => (
          &lt;div key={post._id} className="post-card"&gt;
            &lt;img src={post.imageUrl} alt={post.title} /&gt;
            &lt;h3&gt;{post.title}&lt;/h3&gt;
            &lt;p&gt;{post.description}&lt;/p&gt;
            &lt;button 
              onClick={() => handleDelete(post._id)}
              className="delete-btn"
            &gt;
              删除
            &lt;/button&gt;
          &lt;/div&gt;
        ))}
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

export default MyPosts;